﻿CREATE PROCEDURE [dbo].[Purchase_Authecation_Put]
	@purchaseId bigint,
	@purchaseHashCode nvarchar(128),
	@authecationCode nvarchar(32) = NULL,
	@authecationError nvarchar(32) = NULL,
	@authecationErrorDescription nvarchar(MAX) = NULL,
	@authecationErrorInfo nvarchar(MAX) = NULL
AS
BEGIN
	--DECLARE @chapterHashCode NVARCHAR(128)

	--IF NOT EXISTS (SELECT * FROM [dbo].[purchase_Item] WHERE [PurchaseId] = @purchaseId AND [PurchaseHashCode] = @purchaseHashCode)
	--BEGIN
	--	DECLARE @chapterId UNIQUEIDENTIFIER
	--	SELECT @chapterId = [ChapterId] FROM [dbo].[purchase_Item] WHERE [PurchaseId] = @purchaseId

	--	IF @chapterId IS NOT NULL
	--	BEGIN
	--		SELECT [HashTag] AS [ChapterHashCode] FROM [text_Chapter] WHERE [ChapterId] = @chapterId
	--	END
	--	ELSE 
	--	BEGIN
	--		SELECT @chapterId = [ChapterId] FROM [dbo].[purchase_Item] WHERE [PurchaseHashCode] = @purchaseHashCode

	--		IF @chapterId IS NOT NULL
	--		BEGIN
	--			SELECT [HashTag] AS [ChapterHashCode] FROM [text_Chapter] WHERE [ChapterId] = @chapterId
	--		END

	--	END
	--	RAISERROR ('PurchaseIncorrect',9,1)
	--END
	--ELSE
	IF NOT EXISTS (SELECT * FROM [dbo].[purchase_Item] WHERE [PurchaseId] = @purchaseId AND [PurchaseHashCode] = @purchaseHashCode)
	BEGIN
		RAISERROR ('PurchaseIncorrect',9,1)
		RETURN
	END

	DECLARE @bookHash NVARCHAR(450), @email NVARCHAR(128), @bookId UNIQUEIDENTIFIER, @bookName NVARCHAR(MAX)

	SELECT @email = u.[Email]
	FROM [dbo].[purchase_Item] AS i
	INNER JOIN [dbo].[user_User] AS u ON u.[UserId] = i.[UserId]
	WHERE i.[PurchaseId] = @purchaseId

	SELECT @bookHash = bt.[HashTag], @bookName = [Text]
	FROM [dbo].[text_BookTree] AS bt
	INNER JOIN [dbo].[purchase_Item] AS pitem ON pitem.[BookId] = bt.[BookId]
	--INNER JOIN [dbo].[text_BookTree_Cache] AS btc ON btc.[BookTreeId] = bt.[BookTreeId]
	WHERE [PurchaseId] = @purchaseId AND bt.[LeftKey] = 1

	UPDATE [dbo].[purchase_Item]
	SET [AuthecationDate] = GETUTCDATE()
			,[AuthecationCode] = @authecationCode
			,[AuthecationError] = @authecationError
			,[AuthecationErrorDescription] = @authecationErrorDescription
			,[AuthecationErrorInfo] = @authecationErrorInfo
	WHERE [PurchaseId] = @purchaseId

	SELECT @bookHash AS [BookHash],	@email AS [Email], @bookName AS [BookName]
END